import json
from django.core import serializers
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt

from sjgapp import tool_sjg
from sjgapp.models import mylog

@csrf_exempt
def get_by_page(request):
    info = request.body
    info = json.loads(info)
    pagenow = int(info['pagenow'])
    pagesize = int(info['pagesize'])
    start = (pagenow-1)*pagesize
    end = (pagenow-1)*pagesize+pagesize
    search = info['search']
    mylogs = mylog.objects.filter(name__icontains=search).order_by('-id')[start:end]
    mylogs = serializers.serialize('json', mylogs)

    counts = mylog.objects.filter(name__icontains=search).count()
    return HttpResponse(json.dumps( {"result": json.loads(mylogs), "allcount": counts} ) )

def getlog_by_id(request):
    id = request.GET.get('id')
    mylogresult = mylog.objects.get(pk=id)
    if mylogresult.proxy != 'default':
        tmpresult = str(tool_sjg.ssh_remote_command(mylogresult.proxy, 'cat '+mylogresult.logpath)  , encoding="utf-8")
    else:
        with open(mylogresult.logpath) as f:
            tmpresult = f.read()
    return HttpResponse(json.dumps({'result': tmpresult, 'writeresult':mylogresult.writeresult}))